package com.ls.service;

import com.ls.mapper.PermissionMapper;
import com.ls.model.Permission;
import com.ls.util.BaseMapper;
import com.ls.util.BaseServiceImpl;
import com.ls.util.Tree;
import com.ls.util.TreeUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p></p>
 * Created by zhezhiyong@163.com on 2017/2/10.
 */
@Service
public class PermissionService extends BaseServiceImpl<Permission, Integer> {

    @Resource
    private PermissionMapper permissionMapper;

    @Resource
    private RolePermissionService rolePermissionService;

    @Override
    public BaseMapper getMapper() {
        return permissionMapper;
    }

    public List<Tree> treeList(Integer roleId) {
        List<String> pIds = new ArrayList<>();
        if (null != roleId) pIds = rolePermissionService.selectPermissionIdByRoleId(roleId);
        List<Permission> permissionList = permissionMapper.selectAll();
        List<Tree> trees = new ArrayList<>();
        for (Permission permission : permissionList) {
            Tree tree = new Tree(permission);
            if (pIds.contains(tree.getId())) tree.setChecked(true);
            trees.add(tree);
        }
        List<Tree> newTrees = TreeUtils.getFatherNode(trees);
        return newTrees;
    }

    public List<Permission> findByRoleId(int roleId) {
        return permissionMapper.findByRoleId(roleId);
    }

    public int deleteByParentId(int pid) {
        return permissionMapper.deleteByParentId(pid);
    }
}
